This page last changed on Feb 05, 2010 by brian.

Context and Dependency Injection API

  • Basics @Inject @LoggedIn User user user = what, LoggedIn = which one (not string based!)
  • Can coexist with @Resource and @PostConstruct
  • Can inject fields, methods or constructors
    • Constructor (My prefered type) Example:
      public class CheckoutHandler {
        @Inject
        CheckoutHandler(@LoggedIn User user, 
            PaymentProcessor processor, 
            @Default Card cart) {
          // ...
        }
      }
      
      // Multiple qualifer example
      public class CheckoutHandler {
        @Inject
        CheckoutHandler(@LoggedIn User user, 
            @Reliable
            @PayBy(CREDIT_CARS)
            PaymentProcessor processor, 
            @Default Card cart) {
          // ...
        }
      }
  • Easy to write your own qualifiers. Just create an annotation and annotate it with @Qualifier:
    @Qualifer
    @Retention(RUNTIME)
    @Target({FIELD, TYPE})
    public @interface Red{}
  • ManagedBean
    • Anything injected is a bean. Examples include:
      • EJB Session beans
      • Plain classes with @ManagedBean
      • Any class CDI can discover in a module
      • Example:
        @Reliable
        @PayBy(CREDIT_CARD)
        @ManagedBean
        public class ReliableCreditCardPaymentProcessor implements PaymentProcessor {
        
          void pay(Amount amount) throws PaymentException {
            ...
          }
        }
      • Same example as an EJB:
        @Reliable
        @PayBy(CREDIT_CARD)
        //@ManagedBean
        @Stateless
        public class ReliableCreditCardPaymentProcessor implements PaymentProcessor {
        
          void pay(Amount amount) throws PaymentException {
            ...
          }
        }
      • Same example as a Request-scoped Bean:
        @Reliable
        @PayBy(CREDIT_CARD)
        @RequestScoped
        @ManagedBean
        public class ReliableCreditCardPaymentProcessor implements PaymentProcessor {
        
          void pay(Amount amount) throws PaymentException {
            ...
          }
        }
        • Scopes allowed everywhere: @ApplicationScoped, @RequestScoped
        • Also allowed in web apps: @SessionScoped
  • Named beans. (Built in support for Unified EL)
    • You can name a bean with @Named("cart"). The refer to it in a JSP page using the EL:
      <h.commandButton value="Checkout" action="#{cart.checkout}">
  • Events with annotation-based event model
    • A bean @Observes an event:
      void onLogin(@Observes LoginEvent event) { ...}
      Another bean fires an event using the Event.fire(T event) method
Document generated by Confluence on Feb 03, 2026 15:43